package com.banciyuan.bcywebview.biz.post.uploadpic.services;

import android.app.Service;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.text.TextUtils;

import com.banciyuan.bcywebview.biz.post.uploadpic.receiver.UploaderLoaderInter;
import com.banciyuan.bcywebview.biz.write.photoselecotor.model.PhotoModel;
import com.banciyuan.bcywebview.utils.encrypt.MD5;
import com.banciyuan.bcywebview.utils.file.FileTypeUtil;
import com.banciyuan.bcywebview.utils.file.FileUtils;
import com.banciyuan.bcywebview.utils.file.ImageManager;
import com.banciyuan.bcywebview.utils.sys.SystemUtils;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCancellationSignal;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UpProgressHandler;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.storage.UploadOptions;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import de.greenrobot.daoexample.model.Multi;

/**
 * Created by squall on 2017/4/12.
 */

public class UploadService extends Service {
    /**
     * Creates an IntentService.  Invoked by your subclass's constructor.
     *
     * @param name Used to name the worker thread, important only for debugging.
     */

    private static final String uploadFormat = "%s%s/%s.%s";
    private boolean compress;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String token = intent.getStringExtra("token");
        List<PhotoModel> plist = (List<PhotoModel>) intent.getSerializableExtra("plist");
        compress = intent.getBooleanExtra("compress", false);
        startWork(token, plist);
        return START_NOT_STICKY;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private void startWork(String token, List<PhotoModel> plist) {
        if (!compress) {
            orginThread(token, plist);
        } else {
            compPic(token, plist);
        }
    }

    private void orginThread(final String response, final List<PhotoModel> plist) {
        List<File> mFile = new ArrayList<>();
        if (plist != null) {
            for (PhotoModel p : plist) {
                if (!p.isUpload()) {
                    if (!TextUtils.isEmpty(p.getOriginalPath())) {
                        mFile.add(new File(p.getOriginalPath()));
                    }
                }
            }
            upLoadFile(response, mFile);
        }

    }

    private void compPic(final String response, final List<PhotoModel> plist) {
        new AsyncTask<Void, List<File>, List<File>>() {
            @Override
            protected List<File> doInBackground(Void... params) {
                List<File> mFile = new ArrayList<>();
                for (PhotoModel p : plist) {
                    try {
                        File source = new File(p.getOriginalPath());
                        String srcPath = p.getOriginalPath();
                        String name = MD5.getMD5(srcPath);
                        File file = new File(ImageManager.getTemp(getApplicationContext()) + name);
                        mFile.add(file);
                        if (!new FileTypeUtil().getFileByFile(source).equals("gif")) {
                            int degree = ImageManager.readPictureDegree(srcPath);
                            BitmapFactory.Options newOpts = new BitmapFactory.Options();
                            newOpts.inPreferredConfig = Bitmap.Config.RGB_565;
                            // 开始读入图片，此时把options.inJustDecodeBounds 设回true了
                            newOpts.inJustDecodeBounds = true;
                            Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts); // 此时返回bm为空
                            newOpts.inJustDecodeBounds = false;
                            // 现在主流手机比较多是1080p分辨率，所以高和宽我们设置为
                            float needWidth = 1080f;// 这里设置宽度为1080f
                            int be = 1;// be=1表示不缩放
                            be = (int) (newOpts.outWidth / needWidth);
                            if (be <= 0) be = 1;
                            newOpts.inSampleSize = be;// 设置缩放比例
                            // 重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
                            bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
                            ImageManager.saveTempImageifBig(getApplicationContext(), bitmap, name, true, 1080f, 90, degree);
                        } else {
                            FileUtils.fileChannelCopy(source, file);
                        }
                    } catch (Exception e) {
                        sendFailBroadCast();
                        stopSelf();
                    }
                }
                return mFile;
            }

            @Override
            protected void onPostExecute(List<File> mFile) {
                if (mFile.size() > 0) {
                    upLoadFile(response, mFile);
                }
            }
        }.execute();
    }

    private void upLoadFile(String response, final List<File> mFile) {
        try {
            JSONObject jsonResult = new JSONObject(response).getJSONObject("data");
            String mToken = jsonResult.getString("cloud_upToken");
            String mPrefix = jsonResult.getString("cloud_prefix");
            UploadManager uploadManager = new UploadManager();
            for (final File file : mFile) {
                uploadManager.put(file, getFilename(mPrefix, new FileTypeUtil().getFileByFile(file)), mToken, new UpCompletionHandler() {
                    @Override
                    public void complete(String key, ResponseInfo info, JSONObject response) {
                        Multi multi = null;
                        try {
                            multi = new Multi();
                            if (info.isOK()) {
                                String path = response.getString("key");
                                int h = response.getInt("h");
                                int w = response.getInt("w");
                                multi.setPath(path);
                                multi.setH(h);
                                multi.setW(w);

                                multi.setLocal_path(file.getAbsolutePath());
                                multi.setUpdate_status(true);
                            } else {
                                multi.setLocal_path(file.getAbsolutePath());
                                multi.setUpdate_status(false);
                            }
                        } catch (JSONException e) {
                            multi.setLocal_path(file.getAbsolutePath());
                            multi.setUpdate_status(false);
                        } finally {
                            sendFinishBroadCast(multi);
                            stopSelf();
                        }
                    }
                }, new UploadOptions(null, null, false, new UpProgressHandler() {
                    @Override
                    public void progress(String key, double percent) {
                        sendProgressBroadCast(percent, file.getAbsolutePath());
                    }
                }, new UpCancellationSignal() {
                    @Override
                    public boolean isCancelled() {
                        return false;
                    }
                }));
            }
        } catch (Exception e) {
            sendFailBroadCast();
            stopSelf();
        }
    }

    private void sendFinishBroadCast(Multi multi) {
        Intent intent = new Intent();
        intent.setAction(UploaderLoaderInter.UPLOAD_FINISH_KEY);
        intent.putExtra("Multi", multi);
        sendBroadcast(intent);
    }

    private void sendProgressBroadCast(double progress, String key) {
        Intent intent = new Intent();
        intent.setAction(UploaderLoaderInter.PROGRESS_KEY);
        intent.putExtra("progress", progress);
        intent.putExtra("key", key);
        sendBroadcast(intent);
    }

    private void sendFailBroadCast() {
        Intent intent = new Intent();
        intent.setAction(UploaderLoaderInter.UPLOAD_FAIL_KEY);
        sendBroadcast(intent);
    }

    private String getFilename(String mPrefix, String type) {
        String uniqueid = MD5.getUUID();
        String mDate = Integer.toString(Integer.parseInt(SystemUtils.getDateYmd()), 36);
        return String.format(uploadFormat, mPrefix, mDate, uniqueid, type);
    }

}
